import { useState, useEffect, useContext } from "react";
import { AuthContext } from "@/App";
import { checkLogin } from "@/services/api";
import UserService from "@/services/user";
import AddUserModal from "@/components/AddUserModal";
import { useNavigate } from "react-router-dom";
import { cn } from "@/lib/utils";
import { useTheme } from "@/hooks/useTheme";
import { motion } from "framer-motion";
import { toast } from "sonner";
import { confirm } from "@/lib/dialog";
import { saveProjectContext } from "@/utils/saveProjectContext";

interface Project {
  projectId: string;
  projectName: string;
  projectIcon: string;
  projectDesc: string;
}


interface Team {
  teamId: string;
  teamName: string;
  teamIcon: string;
  desc: string;
  members: {
    userId: string;
    userName: string;
    userIcon: string;
    account: string;
  }[];
  createUser: {
    userId: string;
    userName: string;
    userIcon: string;
    account: string;
    createUser: string;
    createTime: string;
  };
  createTime: string;
  projects?: Array<{
    projectId: string;
    projectName: string;
    projectIcon: string;
    projectDesc: string;
    type: 'OWNER' | 'PARTICIPANT';
    createUser: {
      userId: string;
      userName: string;
      userIcon: string;
      account: string;
    };
    createTime: string;
  }>;
}

export default function TeamList() {
  const { isAuthenticated, userInfo, logout, saveProjectContext, setUserInfo } = useContext(AuthContext);
  const navigate = useNavigate();
  const { theme, toggleTheme, isDark } = useTheme();
  const [teams, setTeams] = useState<Team[]>([]);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showAddMemberModal, setShowAddMemberModal] = useState(false);
  const [showAllMembers, setShowAllMembers] = useState(false);
  const [newTeam, setNewTeam] = useState({
    teamName: "",
    desc: "",
    teamIcon: "fa-solid fa-users"
  });
  const [newMember, setNewMember] = useState({
    account: "",
    role: "member"
  });
  const [editingTeam, setEditingTeam] = useState<Team | null>(null);
  const [selectedTeam, setSelectedTeam] = useState<string | null>(null);
  const [visibleMemberCount, setVisibleMemberCount] = useState(4);
  const [showCreateProjectModal, setShowCreateProjectModal] = useState(false);
  const [newProject, setNewProject] = useState({
    projectName: "",
    projectIcon: "fa-solid fa-folder",
    projectDesc: ""
  });
  const [editingProject, setEditingProject] = useState<Project | null>(null);
  const [showRemoveConfirm, setShowRemoveConfirm] = useState({
    show: false,
    memberId: "",
    memberName: ""
  });
  const [isUpdatingTeam, setIsUpdatingTeam] = useState(false);
  const [showTeamDropdown, setShowTeamDropdown] = useState(false);
  const [showTeamSettingsModal, setShowTeamSettingsModal] = useState(false);
  const [openProjectMenu, setOpenProjectMenu] = useState<string | null>(null);
  const [showProjectMembersModal, setShowProjectMembersModal] = useState(false);
  const [currentProjectMembers, setCurrentProjectMembers] = useState<any[]>([]);
  const [selectedProjectForMembers, setSelectedProjectForMembers] = useState<any>(null);
  const [currentTeamProjects, setCurrentTeamProjects] = useState<any[]>([]);

  useEffect(() => {
    const handleResize = () => {
      const width = window.innerWidth;
      if (width < 640) {
        setVisibleMemberCount(3); // 小屏幕显示3个
      } else if (width < 1024) {
        setVisibleMemberCount(5); // 中等屏幕显示5个
      } else if (width < 1440) {
        setVisibleMemberCount(7); // 大屏幕显示7个
      } else {
        setVisibleMemberCount(9); // 超大屏幕显示9个
      }
    };

    handleResize(); // 初始化
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  const [isLoading, setIsLoading] = useState(true);

  const [members, setMembers] = useState<any[]>([]);
  const [membersLoading, setMembersLoading] = useState(false);
  const [membersError, setMembersError] = useState<string | null>(null);

  // 获取团队成员
  const fetchTeamMembers = async (teamId: string) => {
    try {
      setMembersLoading(true);
      setMembersError(null);
      const members = await UserService.getTeamMembers(teamId);
      setMembers(members);
    } catch (error: any) {
      console.error('获取团队成员失败:', error);
      setMembersError(error.message);
      toast.error(error.message);
    } finally {
      setMembersLoading(false);
    }
  };

  // 点击外部关闭项目操作菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as Element;
      // 检查点击的元素是否在项目操作菜单内
      const isClickInsideMenu = target.closest('.project-menu-container');
      if (openProjectMenu && !isClickInsideMenu) {
        setOpenProjectMenu(null);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [openProjectMenu]);

  const fetchTeams = async () => {
    try {
      setIsLoading(true);
      const userInfo = await UserService.getUserInfo();
      setUserInfo(userInfo);
      const teamList = userInfo.teamList || [];
      // 只保存团队基本信息
      const teamsData = teamList.map((team: any) => ({
        teamId: team.teamId,
        teamName: team.teamName,
        teamIcon: team.teamIcon,
        desc: team.teamDesc,
        isDefault: team.isDefault,
      }));
      setTeams(teamsData);
      // 默认选中团队逻辑
      if (teamsData.length > 0 && !selectedTeam) {
        const defaultTeam = teamsData.find(t => t.isDefault) || teamsData[0];
        setSelectedTeam(defaultTeam.teamId);
        fetchTeamMembers(defaultTeam.teamId);
        // 加载默认团队的项目
        fetchCurrentTeamProjects(defaultTeam.teamId);
      }
    } catch (error) {
      console.error('获取团队失败:', error);
      toast.error('获取团队失败');
    } finally {
      setIsLoading(false);
    }
  };

  // 新增 fetchCurrentTeamProjects 方法
  const fetchCurrentTeamProjects = async (teamId: string) => {
    try {
      const projects = await UserService.getProjectListByTeamId(teamId);
      setCurrentTeamProjects(projects);
    } catch (e) {
      setCurrentTeamProjects([]);
    }
  };

  // 4. useEffect 只调用 fetchTeams
  useEffect(() => {
    fetchTeams();
  }, []);

  useEffect(() => {
    console.log('teams 原始:', teams);
    console.log('teams teamId 列表:', Array.isArray(teams) ? teams.map(t => t.teamId) : teams);
    console.log('userInfo.teamList 原始:', userInfo?.teamList);
    console.log('userInfo.teamList teamId 列表:', Array.isArray(userInfo?.teamList) ? userInfo.teamList.map(t => t.teamId) : userInfo?.teamList);
  }, [teams, userInfo?.teamList]);

  const handleCreateTeam = async () => {
    if (!newTeam.teamName.trim()) {
      toast.error("团队名称不能为空");
      return;
    }

    try {
      // 调用真实接口创建团队
       const res = await UserService.addTeam({
          teamName: newTeam.teamName,
          teamIcon: newTeam.teamIcon,
          teamDesc: newTeam.desc
        });

        if (res.success) {
          // 刷新用户信息
          const userInfo = await UserService.getUserInfo();
        
        const currentUser = {
          userId: "1", // 实际应从AuthContext获取
          userName: "管理员", // 实际应从AuthContext获取
          userIcon: "fa-solid fa-user-shield", // 实际应从AuthContext获取
          account: "admin" // 实际应从AuthContext获取
        };

        const team: Team = {
          teamId: Date.now().toString(), // 实际应从接口返回获取
          teamName: newTeam.teamName,
          teamIcon: newTeam.teamIcon,
          desc: newTeam.desc,
          members: [currentUser],
          createUser: currentUser,
          createTime: new Date().toISOString()
        };

        setTeams([...teams, team]);
        setSelectedTeam(team.teamId);
        setShowCreateModal(false);
        setNewTeam({ teamName: "", desc: "", teamIcon: "fa-solid fa-users" });
        toast.success(`团队 ${team.teamName} 创建成功`);
      }
    } catch (error: any) {
      console.error('创建团队错误:', error);
      toast.error(error.message || '创建团队失败');
    }
  };

  const handleAddMember = () => {
    if (!newMember.account.trim()) {
      toast.error("请输入成员账号");
      return;
    }

    if (!selectedTeam) return;

    const updatedTeams = teams.map(team => {
      if (team.teamId === selectedTeam) {
        return {
          ...team,
          members: [
            ...team.members,
            {
              userId: Date.now().toString(),
              userName: `用户${team.members.length + 1}`,
              userIcon: "fa-solid fa-user",
              account: newMember.account
            }
          ]
        };
      }
      return team;
    });

    setTeams(updatedTeams);
    setShowAddMemberModal(false);
    setNewMember({ account: "", role: "member" });
    toast.success("成员添加成功");
  };

  const handleRemoveMember = async (userId: string) => {
    if (!selectedTeam) return;

    // 检查是否为创建者
    const memberToRemove = members.find(m => m.userId === userId);
    if (memberToRemove?.type === 'OWNER') {
      toast.error("创建者不能被移除");
      return;
    }

    try {
      // 调用接口移除团队成员
      const res = await UserService.deleteTeamUser({
        teamUserList: [{
          userId: userId,
          teamId: selectedTeam
        }]
      });

      if (res.success) {
        // 更新本地团队成员列表
    const updatedTeams = teams.map(team => {
      if (team.teamId === selectedTeam) {
        return {
          ...team,
          members: team.members.filter(m => m.userId !== userId)
        };
      }
      return team;
    });

    setTeams(updatedTeams);
        
        // 刷新团队成员数据
        try {
          const members = await UserService.getTeamMembers(selectedTeam);
          setMembers(members);
        } catch (error) {
          console.error('刷新团队成员失败:', error);
        }
        
    toast.success("成员已移除");
      } else {
        toast.error(res.message || "移除成员失败");
      }
    } catch (error: any) {
      console.error('移除成员失败:', error);
      toast.error(error.message || '移除成员失败');
    }
  };

  const handleUpdateTeam = async () => {
    if (!editingTeam || !editingTeam.teamName.trim()) {
      toast.error("团队名称不能为空");
      return;
    }

    setIsUpdatingTeam(true);
    try {
      const res = await UserService.editTeam({
        teamId: editingTeam.teamId,
        teamName: editingTeam.teamName,
        teamDesc: editingTeam.desc
      });

      if (res.success) {
        setTeams(teams.map(t => 
          t.teamId === editingTeam.teamId ? editingTeam : t
        ));
        setEditingTeam(null);
        toast.success("团队信息已更新");
      }
    } catch (error: any) {
      console.error('更新团队信息失败:', error);
      toast.error(error.message || '更新团队信息失败');
    } finally {
      setIsUpdatingTeam(false);
    }
  };

  const handleDeleteTeam = async (teamId: string) => {
    const team = teams.find(t => t.teamId === teamId);
    if (!team) {
      toast.error('团队不存在');
      return;
    }

    // 检查当前用户是否为团队拥有者
    const currentUser = userInfo;
    if (!currentUser) {
      toast.error('用户信息获取失败');
      return;
    }

    // 检查用户在该团队中的角色
    const userTeam = currentUser.teamList.find(t => t.teamId === teamId);
    if (!userTeam) {
      toast.error('您不是该团队成员');
      return;
    }

    if (userTeam.type !== 'OWNER') {
      toast.error('只有团队拥有者才能删除团队');
      return;
    }

    try {
      // 调用删除团队接口
      const res = await UserService.deleteTeam({
        teamId: teamId
      });

      if (res.success) {
        // 从本地状态中移除团队
        setTeams(teams.filter(t => t.teamId !== teamId));
        
        // 如果删除的是当前选中的团队，取消选中
        if (selectedTeam === teamId) {
          setSelectedTeam(null);
        }
        
        toast.success(`团队 ${team.teamName} 已删除`);
      } else {
        toast.error(res.message || '删除团队失败');
      }
    } catch (error: any) {
      console.error('删除团队失败:', error);
      toast.error(error.message || '删除团队失败');
    }
  };

  // 退出团队
  // 获取项目成员
  const fetchProjectMembers = async (projectId: string) => {
    try {
      const members = await UserService.getProjectMembers(projectId);
      setCurrentProjectMembers(members);
    } catch (error: any) {
      console.error('获取项目成员失败:', error);
      toast.error(error.message || '获取项目成员失败');
    }
  };

  // 打开项目成员管理模态框
  const handleOpenProjectMembers = async (project: any) => {
    setSelectedProjectForMembers(project);
    setShowProjectMembersModal(true);
    setOpenProjectMenu(null);
    await fetchProjectMembers(project.projectId);
  };

  // 添加项目成员
  const handleAddProjectMember = async (userId: string, permission: 'r' | 'rw') => {
    if (!selectedProjectForMembers) return;
    
    try {
      await UserService.addProjectUser({
        projectUserList: [{
          projectId: selectedProjectForMembers.projectId,
          userId: userId,
          permission: permission
        }]
      });
      
      // 刷新项目成员列表
      await fetchProjectMembers(selectedProjectForMembers.projectId);
      toast.success('项目成员添加成功');
    } catch (error: any) {
      toast.error(error.message || '添加项目成员失败');
    }
  };

  // 移除项目成员
  const handleRemoveProjectMember = async (userId: string) => {
    if (!selectedProjectForMembers) return;
    
    try {
      await UserService.deleteProjectUser({
        projectUserList: [{
          projectId: selectedProjectForMembers.projectId,
          userId: userId
        }]
      });
      
      // 刷新项目成员列表
      await fetchProjectMembers(selectedProjectForMembers.projectId);
      toast.success('项目成员移除成功');
    } catch (error: any) {
      toast.error(error.message || '移除项目成员失败');
    }
  };

  // 更新项目成员权限
  const handleUpdateProjectPermission = async (userId: string, permission: 'r' | 'rw') => {
    if (!selectedProjectForMembers) return;
    
    try {
      await UserService.updateProjectPermission({
        projectId: selectedProjectForMembers.projectId,
        userId: userId,
        permission: permission
      });
      
      // 刷新项目成员列表
      await fetchProjectMembers(selectedProjectForMembers.projectId);
      toast.success('权限更新成功');
    } catch (error: any) {
      toast.error(error.message || '更新权限失败');
    }
  };

  // 检查当前用户在选中团队中的角色
  const getCurrentUserTeamRole = () => {
    if (!selectedTeam || !userInfo?.teamList) return null;
    const userTeam = userInfo.teamList.find(t => t.teamId === selectedTeam);
    return userTeam?.type || null;
  };

  // 检查是否可以创建项目（只有团队拥有者可以创建项目）
  const canCreateProject = () => {
    const role = getCurrentUserTeamRole();
    return role === 'OWNER';
  };

  // 退出项目
  const handleLeaveProject = async (project: any) => {
    try {
      await UserService.deleteProjectUser({
        projectUserList: [{
          projectId: project.projectId,
          userId: (userInfo as any).userId
        }]
      });
      
      // 从本地状态中移除项目
      const updatedTeams = teams.map(team => {
        if (team.teamId === selectedTeam) {
          return {
            ...team,
            projects: team.projects?.filter(p => p.projectId !== project.projectId) || []
          };
        }
        return team;
      });
      setTeams(updatedTeams);
      setOpenProjectMenu(null);
      toast.success(`已退出项目 ${project.projectName}`);
    } catch (error: any) {
      toast.error(error.message || '退出项目失败');
    }
  };

  const handleLeaveTeam = async (teamId: string) => {
    const team = teams.find(t => t.teamId === teamId);
    if (!team) {
      toast.error('团队不存在');
      return;
    }

    // 检查当前用户是否为团队参与者
    const currentUser = userInfo;
    if (!currentUser) {
      toast.error('用户信息获取失败');
      return;
    }

    // 检查用户在该团队中的角色
    const userTeam = currentUser.teamList.find(t => t.teamId === teamId);
    if (!userTeam) {
      toast.error('您不是该团队成员');
      return;
    }

    if (userTeam.type === 'OWNER') {
      toast.error('团队拥有者不能退出团队，请使用删除团队功能');
      return;
    }

    try {
      // 调用退出团队接口（使用删除团队成员接口）
      const res = await UserService.deleteTeamUser({
        teamUserList: [{
          userId: currentUser.userId,
          teamId: teamId
        }]
      });

      if (res.success) {
        // 从本地状态中移除团队
        setTeams(teams.filter(t => t.teamId !== teamId));
        
        // 如果退出的是当前选中的团队，取消选中
        if (selectedTeam === teamId) {
          setSelectedTeam(null);
        }
        
        toast.success(`已退出团队 ${team.teamName}`);
      } else {
        toast.error(res.message || '退出团队失败');
      }
    } catch (error: any) {
      console.error('退出团队失败:', error);
      toast.error(error.message || '退出团队失败');
    }
  };

  const iconOptions = [
    "fa-solid fa-users",
    "fa-solid fa-code",
    "fa-solid fa-server",
    "fa-solid fa-mobile-screen",
    "fa-solid fa-database",
    "fa-solid fa-cloud",
    "fa-solid fa-shield-halved"
  ];

  const roleOptions = [
    { value: "admin", label: "管理员" },
    { value: "member", label: "普通成员" }
  ];

  const currentTeam = teams.find(t => t.teamId === selectedTeam);

  // 点击外部关闭下拉菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as Element;
      if (!target.closest('.team-dropdown')) {
        setShowTeamDropdown(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  // 在 TeamList 组件内部补充 handleDeleteProject 方法
  const handleDeleteProject = async (projectId: string) => {
    if (!selectedTeam) return;
    try {
      const res = await UserService.deleteProject({ projectId });
      if (res.success) {
        toast.success('项目已删除');
        // 删除后刷新项目列表
        fetchCurrentTeamProjects(selectedTeam);
      } else {
        toast.error(res.message || '删除项目失败');
      }
    } catch (error: any) {
      toast.error(error?.message || '删除项目失败');
    }
  };

  return (
    <div className={cn(
      "min-h-screen flex flex-col bg-transparent",
      isDark ? "text-gray-100" : "text-gray-900"
    )}>
      {/* 导航栏 */}
      <header className={cn(
        "sticky top-0 z-10 p-2 border-b backdrop-blur-sm",
        isDark ? "bg-gray-800/95 border-gray-700" : "bg-white/95 border-gray-200"
      )}>
        <div className="container mx-auto flex justify-between items-center">
          <div className="flex items-center space-x-4">
            <button 
              onClick={async () => {
                try {
                  const isLoggedIn = await checkLogin();
                  if (!isLoggedIn) {
                    toast.error('登录已过期，请重新登录');
                    navigate("/login");
                  } else {
                    navigate("/");  // 返回到首页
                  }
                } catch (error) {
                  console.error('检查登录状态失败:', error);
                  toast.error('检查登录状态失败');
                  navigate("/login");
                }
              }}
              className={cn(
                "px-3 py-1.5 rounded-lg font-mono flex items-center transition-all duration-200",
                "hover:scale-105",
                isDark ? "hover:bg-gray-700" : "hover:bg-gray-100"
              )}
            >
              <i className="fa-solid fa-home mr-2"></i>
              返回首页
            </button>
            
            {/* 团队切换下拉菜单 */}
            <div className="relative flex items-center space-x-3 team-dropdown">
              <div className="relative group">
                <button
                  onClick={() => setShowTeamDropdown(!showTeamDropdown)}
                  className={cn(
                    "pl-10 pr-8 py-2 rounded-xl font-mono transition-all duration-200 flex items-center justify-between min-w-[180px]",
                    "focus:outline-none focus:ring-2 focus:ring-offset-2",
                    isDark 
                      ? "bg-gray-700 border-gray-600 focus:ring-blue-500 focus:border-blue-500 hover:bg-gray-600" 
                      : "bg-white border-gray-300 focus:ring-orange-500 focus:border-orange-500 hover:bg-gray-50"
                  )}
                >
                  <span className="flex items-center">
                {selectedTeam && (
                    <i className={cn(
                      teams.find(t => t.teamId === selectedTeam)?.teamIcon,
                        "text-lg mr-2",
                      isDark ? "text-blue-400" : "text-orange-500"
                    )}></i>
                    )}
                    {selectedTeam ? teams.find(t => t.teamId === selectedTeam)?.teamName : "选择团队"}
                  </span>
                  <i className="fa-solid fa-chevron-down text-sm opacity-70 transition-transform group-hover:rotate-180"></i>
                </button>
                
                {/* 下拉菜单 */}
                {showTeamDropdown && (
                  <div className="absolute top-full left-0 mt-1 w-full rounded-xl shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 border border-gray-200 dark:border-gray-700 z-50">
                    <div className="py-1">
                      {teams.map(team => {
                        const userTeam = userInfo?.teamList.find(t => t.teamId === team.teamId);
                        const isOwner = userTeam?.type === 'OWNER';
                        const isSelected = selectedTeam === team.teamId;
                        
                        return (
                          <div key={team.teamId} className="relative">
                            <button
                              onClick={async () => {
                                await UserService.setDefaultTeam(team.teamId);
                                const userInfo = await UserService.getUserInfo();
                                setUserInfo(userInfo);
                                setSelectedTeam(team.teamId);
                                fetchTeamMembers(team.teamId);
                                fetchCurrentTeamProjects(team.teamId);
                                setShowTeamDropdown(false);
                              }}
                              className={cn(
                                "w-full text-left px-4 py-2 text-sm transition-colors duration-200 flex items-center justify-between",
                                isSelected 
                                  ? (isDark ? "bg-blue-600 text-white" : "bg-blue-500 text-white")
                                  : (isDark ? "text-gray-200 hover:bg-gray-700" : "text-gray-700 hover:bg-gray-100")
                              )}
                            >
                              <div className="flex items-center flex-1 min-w-0">
                                <i className={cn(
                                  team.teamIcon,
                                  "text-lg mr-2 flex-shrink-0",
                                  isSelected ? "text-white" : (isDark ? "text-blue-400" : "text-orange-500")
                                )}></i>
                                <span 
                                  className="truncate"
                                  title={team.teamName}
                                >
                                  {team.teamName}
                                </span>
                              </div>
                              <span className={cn(
                                "ml-2 px-2 py-0.5 rounded-full text-xs flex-shrink-0",
                                isOwner 
                                  ? (isSelected ? "bg-yellow-200 text-yellow-800" : "bg-yellow-100 text-yellow-700")
                                  : (isSelected ? "bg-gray-200 text-gray-800" : "bg-gray-100 text-gray-600")
                              )}>
                                {isOwner ? '拥有者' : '参与者'}
                              </span>
                            </button>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
          
          <div className="flex items-center space-x-3">
                    <button
                     onClick={() => setShowCreateModal(true)}
                     className={cn(
               "px-4 py-1.5 rounded-lg font-medium transition-all duration-200 transform hover:scale-105",
                 isDark 
                 ? "bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700" 
                 : "bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600",
               "text-white shadow-lg hover:shadow-xl"
               )}
             >
               <i className="fa-solid fa-plus mr-2"></i>
               新建团队
             </button>
             <button 
               onClick={toggleTheme}
               className={cn(
                "w-8 h-8 rounded-lg flex items-center justify-center transition-all duration-200",
                "hover:scale-105",
                 isDark ? "bg-gray-700 hover:bg-gray-600" : "bg-gray-200 hover:bg-gray-300"
               )}
              title={isDark ? "切换到浅色模式" : "切换到深色模式"}
             >
               <i className={isDark ? "fa-solid fa-sun" : "fa-solid fa-moon"}></i>
             </button>
             <div className="relative group">
               <button className="flex items-center">
                <div className={cn(
                  "w-8 h-8 rounded-lg flex items-center justify-center transition-all duration-200",
                  "hover:scale-105",
                  isDark ? "bg-gray-700 hover:bg-gray-600" : "bg-gray-200 hover:bg-gray-300"
                )}>
                   {isAuthenticated && userInfo?.userIcon ? (
                     <i className={cn(
                       userInfo.userIcon,
                       "text-lg",
                       isDark ? "text-blue-400" : "text-orange-500"
                     )}></i>
                   ) : (
                     <i className="fa-solid fa-user text-gray-600 dark:text-gray-300"></i>
                   )}
                 </div>
               </button>
               {isAuthenticated && (
                <div className="absolute right-0 mt-2 w-48 rounded-xl shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 invisible group-hover:visible transition-all border border-gray-200 dark:border-gray-700">
                   <div className="py-1">
                    <div className="px-4 py-2 text-sm text-gray-700 dark:text-gray-200 border-b border-gray-200 dark:border-gray-700">
                       {userInfo?.userName || '用户'}
                     </div>
                     <button 
                       onClick={logout}
                      className="block w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors duration-200"
                     >
                       <i className="fa-solid fa-right-from-bracket mr-2"></i>
                       退登
                     </button>
                   </div>
                 </div>
               )}
             </div>
           </div>
        </div>
      </header>

      {/* 主内容 */}
      <main className="flex-1 container mx-auto p-1 md:p-2">
          {isLoading ? (
            <div className="flex flex-col items-center justify-center h-full py-12">
              <div className="relative">
                <i className="fa-solid fa-spinner fa-spin text-4xl mb-4 text-blue-500"></i>
                <div className="absolute inset-0 rounded-full border-2 border-blue-200 animate-ping"></div>
              </div>
              <p className="font-mono text-lg">加载团队数据中...</p>
            </div>
          ) : teams.length === 0 ? (
            <div className="flex flex-col items-center justify-center h-full py-12">
              <div className="relative mb-8">
                <i className="fa-solid fa-users text-6xl opacity-20"></i>
                <div className="absolute inset-0 bg-gradient-to-r from-blue-400 to-purple-500 bg-clip-text text-transparent">
                  <i className="fa-solid fa-users text-6xl"></i>
                </div>
              </div>
              <h2 className="text-2xl font-mono mb-4 text-center">您还没有任何团队</h2>
              <p className="text-gray-500 mb-6 text-center max-w-md">创建一个团队开始协作，与团队成员一起管理项目和文档</p>
              <button 
                onClick={() => setShowCreateModal(true)}
                className={cn(
                  "px-8 py-3 rounded-lg font-medium transition-all duration-200 transform hover:scale-105",
                  isDark 
                    ? "bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700" 
                    : "bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600",
                  "text-white shadow-lg hover:shadow-xl"
                )}
              >
                <i className="fa-solid fa-plus mr-2"></i>
                创建第一个团队
              </button>
            </div>
          ) : !selectedTeam && (
            <div className="flex flex-col items-center justify-center h-full py-12">
              <div className="relative mb-8">
                <i className="fa-solid fa-hand-point-up text-6xl opacity-20"></i>
                <div className="absolute inset-0 bg-gradient-to-r from-green-400 to-blue-500 bg-clip-text text-transparent">
                  <i className="fa-solid fa-hand-point-up text-6xl"></i>
                </div>
              </div>
              <h2 className="text-2xl font-mono mb-4 text-center">请选择一个团队</h2>
              <p className="text-gray-500 text-center max-w-md">从上方下拉菜单中选择您要管理的团队</p>
            </div>
          )}
          {selectedTeam && (
            <div className="grid grid-cols-1 min-[350px]:grid-cols-4 gap-2 h-[calc(100vh-100px)]">
              {/* 左侧：团队卡片和成员列表 */}
              <div className="min-[350px]:col-span-1 flex flex-col space-y-2">
                {/* 团队概览卡片 - 正方形布局 */}
                <motion.div
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  className={cn(
                    "w-full h-40 p-4 rounded-xl shadow-lg border flex flex-col justify-center items-center text-center flex-shrink-0 relative group",
                    isDark ? "bg-gray-800 border-gray-700" : "bg-white border-gray-200"
                  )}
                >
                  {/* 设置按钮 - 只有拥有者可见 */}
                  {(() => {
                    const userTeam = userInfo?.teamList.find(t => t.teamId === selectedTeam);
                    const isOwner = userTeam?.type === 'OWNER';
                    
                    return isOwner ? (
                      <button
                        onClick={() => {
                          if (!selectedTeam) {
                            toast.error('请先选择一个团队');
                            return;
                          }
                          setShowTeamSettingsModal(true);
                        }}
                        className={cn(
                          "absolute top-2 right-2 w-8 h-8 rounded-lg flex items-center justify-center transition-all duration-200 opacity-0 group-hover:opacity-100",
                          "hover:scale-110",
                          isDark ? "bg-gray-700 hover:bg-gray-600 text-blue-400" : "bg-gray-100 hover:bg-gray-200 text-blue-500"
                        )}
                        title="团队设置"
                      >
                        <i className="fa-solid fa-cog text-sm"></i>
                      </button>
                    ) : (
                      <button
                        onClick={async () => {
                          if (!selectedTeam) {
                            toast.error('请先选择一个团队');
                            return;
                          }
                          
                          const confirmed = await confirm.warning(
                            '退出团队',
                            `确定要退出团队 "${currentTeam?.teamName}" 吗？\n\n退出后您将无法访问该团队的项目和文档。`,
                            '退出',
                            '取消'
                          );
                          
                          if (confirmed) {
                            await handleLeaveTeam(selectedTeam);
                          }
                        }}
                        className={cn(
                          "absolute top-2 right-2 w-8 h-8 rounded-lg flex items-center justify-center transition-all duration-200 opacity-0 group-hover:opacity-100",
                          "hover:scale-110",
                          isDark ? "bg-gray-700 hover:bg-gray-600 text-orange-400" : "bg-gray-100 hover:bg-gray-200 text-orange-500"
                        )}
                        title="退出团队"
                      >
                        <i className="fa-solid fa-sign-out-alt text-sm"></i>
                      </button>
                    );
                  })()}

                  <div className={cn(
                    "w-12 h-12 rounded-xl flex items-center justify-center mb-3 -ml-2",
                    isDark ? "bg-gradient-to-br from-blue-600 to-purple-600" : "bg-gradient-to-br from-orange-500 to-red-500"
                  )}>
                    <i className={cn(
                      currentTeam?.teamIcon,
                      "text-xl text-white"
                    )}></i>
                  </div>
                  <h1 className="text-lg font-bold font-mono mb-1">{currentTeam?.teamName}</h1>
                  <p className="text-gray-500 text-xs mb-2 line-clamp-2">{currentTeam?.desc || '暂无描述'}</p>
                  <div className="text-xs text-gray-500">
                    {members.length}位成员 · {currentTeam?.projects?.length || 0}个项目
                  </div>
                </motion.div>

                {/* 团队成员列表 */}
                <motion.div
                  initial={{ opacity: 0, x: -20 }}
                  animate={{ opacity: 1, x: 0 }}
                  className={cn(
                    "p-3 rounded-xl shadow-lg border flex-1 overflow-hidden flex flex-col min-h-0",
                    isDark ? "bg-gray-800 border-gray-700" : "bg-white border-gray-200"
                  )}
                  style={{ maxHeight: 'calc(100vh - 260px)' }}
                >
                  <div className="flex items-center justify-between mb-3 flex-shrink-0">
                    <h3 className="font-mono text-base font-semibold">团队成员</h3>
                    <span className={cn(
                      "px-2 py-0.5 rounded-full text-xs font-medium",
                      isDark ? "bg-blue-900 text-blue-200" : "bg-blue-100 text-blue-800"
                    )}>
                      {members.length}位
                  </span>
                </div>
                  
                  <div 
                    className="space-y-1 flex-1 overflow-y-auto min-h-0 pr-1 custom-scrollbar"
                    style={{ maxHeight: 'calc(100vh - 320px)' }}
                  >
                   {membersLoading ? (
                      <div className="flex items-center justify-center py-6">
                        <i className="fa-solid fa-spinner fa-spin text-lg mr-2 text-blue-500"></i>
                        <span className="text-sm">加载中...</span>
                     </div>
                   ) : membersError ? (
                      <div className="text-red-500 p-3 text-center rounded-lg bg-red-50 dark:bg-red-900/20">
                        <p className="text-sm mb-2">{membersError}</p>
                       <button 
                         onClick={() => selectedTeam && fetchTeamMembers(selectedTeam)}
                          className="px-2 py-1 rounded-md text-xs bg-red-100 hover:bg-red-200 dark:bg-red-800 dark:hover:bg-red-700"
                       >
                         重试
                       </button>
                     </div>
                    ) : members.map((member, index) => (
                       <motion.div
                        key={member.userId}
                        initial={{ opacity: 0, x: -20 }}
                        animate={{ opacity: 1, x: 0 }}
                        transition={{ delay: index * 0.1 }}
                        whileHover={{ scale: 1.02 }}
                        whileTap={{ scale: 0.98 }}
                        className={cn(
                          "flex items-center space-x-2 p-1.5 rounded-lg transition-all duration-200",
                          isDark ? "hover:bg-gray-700/50" : "hover:bg-gray-50"
                        )}
                      >
                        <div className="relative">
                       <div className={cn(
                            "w-10 h-10 rounded-lg flex items-center justify-center relative overflow-hidden",
                            isDark ? "bg-gradient-to-br from-gray-700 to-gray-600" : "bg-gradient-to-br from-gray-100 to-gray-200"
                       )}>
                         <i className={cn(
                           member.type === 'OWNER' ? "fa-solid fa-crown" : member.userIcon,
                              "text-lg",
                              member.type === 'OWNER' 
                                ? "text-yellow-500" 
                                : (isDark ? "text-blue-400" : "text-orange-500")
                         )}></i>
                       </div>
                       {member.type === 'PARTICIPANT' && (
                          <button
                            onClick={async (e) => {
                              e.stopPropagation();
                              setShowRemoveConfirm({
                                show: true,
                                memberId: member.userId,
                                memberName: member.userName
                              });
                            }}
                           className={cn(
                                "absolute -top-1 -right-1 w-4 h-4 rounded-full flex items-center justify-center text-xs",
                                "bg-red-500 text-white opacity-0 group-hover:opacity-100 transition-all duration-200",
                                "hover:bg-red-600 transform hover:scale-110"
                           )}
                           title="移出团队"
                         >
                           <i className="fa-solid fa-xmark"></i>
                         </button>
                       )}
                        </div>
                        
                        <div className="flex-1 min-w-0">
                          <p className="font-medium text-sm truncate">{member.userName}</p>
                          <div className="flex items-center space-x-1 mt-0.5">
                         {member.type === 'PARTICIPANT' && (
                              <span className={cn(
                                "px-1.5 py-0.5 rounded-full text-xs font-medium",
                                "bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300"
                              )}>
                                <i className="fa-solid fa-user mr-0.5"></i>
                             参与者
                           </span>
                         )}
                         {member.type === 'OWNER' && (
                              <span className={cn(
                                "px-1.5 py-0.5 rounded-full text-xs font-medium",
                                "bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300"
                              )}>
                                <i className="fa-solid fa-crown mr-0.5"></i>
                             管理员
                           </span>
                         )}
                          </div>
                        </div>
                    </motion.div>
                  ))}
                </div>
                </motion.div>
            </div>

              {/* 右侧：项目列表 */}
                <motion.div
                initial={{ opacity: 0, x: 20 }}
                animate={{ opacity: 1, x: 0 }}
                  className={cn(
                  "min-[350px]:col-span-3 p-3 rounded-xl shadow-lg border overflow-hidden flex flex-col min-h-0",
                  isDark ? "bg-gray-800 border-gray-700" : "bg-white border-gray-200"
                )}
                style={{ maxHeight: 'calc(100vh - 100px)' }}
              >
                <div className="flex items-center justify-between mb-3 flex-shrink-0">
                        <div>
                    <h3 className="font-mono text-lg font-semibold mb-1">团队项目</h3>
                    <p className="text-gray-500 text-sm">管理和查看团队的所有项目</p>
                        </div>
                  <div className="flex items-center space-x-3">
                    <span className={cn(
                      "px-2 py-1 rounded-full text-sm font-medium",
                      isDark ? "bg-orange-900 text-orange-200" : "bg-orange-100 text-orange-800"
                    )}>
                    {currentTeam?.projects?.length || 0}个项目
                  </span>
                  {canCreateProject() ? (
                    <button
                      onClick={() => setShowCreateProjectModal(true)}
                      className={cn(
                        "px-4 py-2 rounded-lg font-medium transition-all duration-200 transform hover:scale-105",
                        isDark 
                          ? "bg-gradient-to-r from-orange-600 to-red-600 hover:from-orange-700 hover:to-red-700" 
                          : "bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600",
                        "text-white shadow-lg hover:shadow-xl"
                      )}
                    >
                      <i className="fa-solid fa-plus mr-2"></i>
                      新建项目
                    </button>
                  ) : (
                    <button
                      disabled
                      className={cn(
                        "px-4 py-2 rounded-lg font-medium transition-all duration-200 transform",
                        isDark 
                          ? "bg-gray-600 text-gray-400 cursor-not-allowed" 
                          : "bg-gray-300 text-gray-500 cursor-not-allowed",
                        "shadow-lg"
                      )}
                      title="只有团队拥有者可以创建项目"
                    >
                      <i className="fa-solid fa-plus mr-2"></i>
                      新建项目
                    </button>
                  )}
                </div>
              </div>

                <div className="overflow-y-auto flex-1 min-h-0 pr-1 custom-scrollbar">
                  {currentTeamProjects && currentTeamProjects.length > 0 ? (
                    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
                      {currentTeamProjects.map((project, index) => (
                        <motion.div
                          key={project.projectId}
                          initial={{ opacity: 0, y: 20 }}
                          animate={{ opacity: 1, y: 0 }}
                          transition={{ delay: index * 0.1 }}
                          whileHover={{ y: -5, scale: 1.02 }}
                          whileTap={{ scale: 0.98 }}
                          className={cn(
                            "group relative p-4 rounded-xl shadow-lg border cursor-pointer transition-all duration-300",
                            "hover:shadow-xl",
                            // 根据项目类型设置不同的边框颜色
                            (project as any).type === 'OWNER' 
                              ? (isDark ? "bg-gray-800 border-yellow-500/50 hover:border-yellow-400" : "bg-white border-yellow-300 hover:border-yellow-400")
                              : (project as any).type === 'PARTICIPANT'
                                ? (isDark ? "bg-gray-800 border-green-500/50 hover:border-green-400" : "bg-white border-green-300 hover:border-green-400")
                                : (isDark ? "bg-gray-800 border-gray-700 hover:border-gray-600" : "bg-white border-gray-200 hover:border-gray-300")
                          )}
                          style={{ aspectRatio: '2/1' }}
                          onClick={async () => {
                            try {
                              if (project.projectId && selectedTeam) {
                                saveProjectContext(project.projectId, selectedTeam, project.type, project.permission);
                                localStorage.setItem('currentProjectType', project.type);
                                localStorage.setItem('currentProjectPermission', project.permission);
                              }
                              // 添加短暂延迟确保上下文保存完成
                              await new Promise(resolve => setTimeout(resolve, 50));
                              navigate('/project-detail');
                            } catch (error) {
                              console.error('跳转项目详情页失败:', error);
                              toast.error('跳转失败，请重试');
                            }
                          }}
                        >
                          {/* 操作按钮 */}
                          <div className="absolute top-2 right-2 z-10 project-menu-container flex space-x-2">
                            {/* 参与者退出项目按钮 */}
                            {(project as any).type === 'PARTICIPANT' && (
                              <button
                                onClick={async (e) => {
                                  e.stopPropagation();
                                  const confirmed = await confirm.warning(
                                    '退出项目',
                                    `确定要退出项目 "${project.projectName}" 吗？\n\n退出后您将无法访问该项目的文档。`,
                                    '退出',
                                    '取消'
                                  );
                                  if (confirmed) {
                                    await handleLeaveProject(project);
                                  }
                                }}
                                className={cn(
                                  "w-8 h-8 rounded-lg flex items-center justify-center transition-all duration-200",
                                  isDark ? "bg-gray-700 hover:bg-gray-600 text-orange-400" : "bg-gray-100 hover:bg-gray-200 text-orange-500",
                                  "hover:scale-110"
                                )}
                                title="退出项目"
                              >
                                <i className="fa-solid fa-sign-out-alt text-xs"></i>
                              </button>
                            )}
                            {/* 其它操作按钮（如拥有者的更多菜单） */}
                            {(project as any).type === 'OWNER' && (
                              <div className="relative project-menu-container" style={{ display: 'inline-block' }}>
                                <button
                                  onClick={(e) => {
                                    e.stopPropagation();
                                    setOpenProjectMenu(openProjectMenu === project.projectId ? null : project.projectId);
                                  }}
                                  className={cn(
                                    "w-8 h-8 rounded-lg flex items-center justify-center transition-all duration-200 opacity-0 group-hover:opacity-100",
                                    isDark ? "bg-gray-700 hover:bg-gray-600" : "bg-gray-100 hover:bg-gray-200",
                                    "hover:scale-110"
                                  )}
                                  title="项目操作"
                                >
                                  <i className="fa-solid fa-ellipsis-vertical text-xs"></i>
                                </button>
                                {openProjectMenu === project.projectId && (
                                  <div
                                    className="absolute right-0 mt-2 w-32 bg-white dark:bg-gray-800 shadow-lg rounded-md border border-gray-100 dark:border-gray-700 z-50"
                                    onClick={e => e.stopPropagation()}
                                  >
                                    <button
                                      onClick={e => {
                                        e.stopPropagation();
                                        handleOpenProjectMembers(project);
                                        setOpenProjectMenu(null);
                                      }}
                                      className="block w-full text-left px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-700"
                                    >
                                      <i className="fa-solid fa-users mr-2"></i>项目成员
                                    </button>
                                    <button
                                      onClick={e => {
                                        e.stopPropagation();
                                        setEditingProject(project);
                                        setOpenProjectMenu(null);
                                      }}
                                      className="block w-full text-left px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-700"
                                    >
                                      <i className="fa-solid fa-pen mr-2"></i>编辑
                                    </button>
                                    <button
                                      onClick={async e => {
                                        e.stopPropagation();
                                        setOpenProjectMenu(null);
                                        const confirmed = await confirm.warning(
                                          '删除项目',
                                          `确定要删除项目 "${project.projectName}" 吗？\n\n删除后不可恢复。`,
                                          '删除',
                                          '取消'
                                        );
                                        if (confirmed) {
                                          handleDeleteProject(project.projectId);
                                        }
                                      }}
                                      className="block w-full text-left px-4 py-2 text-sm hover:bg-red-100 dark:hover:bg-red-700 text-red-600 dark:text-red-400"
                                    >
                                      <i className="fa-solid fa-trash mr-2"></i>删除
                                    </button>
                                  </div>
                                )}
                              </div>
                            )}
                          </div>

                          {/* 项目内容 */}
                          <div className="space-y-2">
                            <div className="flex items-center space-x-2">
                              <div className={cn(
                                "w-8 h-8 rounded-lg flex items-center justify-center",
                                // 根据项目类型设置不同的图标背景色
                                (project as any).type === 'OWNER'
                                  ? (isDark ? "bg-gradient-to-br from-yellow-600 to-orange-600" : "bg-gradient-to-br from-yellow-500 to-orange-500")
                                  : (project as any).type === 'PARTICIPANT'
                                    ? (isDark ? "bg-gradient-to-br from-green-600 to-blue-600" : "bg-gradient-to-br from-green-500 to-blue-500")
                                    : (isDark ? "bg-gradient-to-br from-blue-600 to-purple-600" : "bg-gradient-to-br from-blue-500 to-purple-500")
                              )}>
                         <i className={cn(
                           project.projectIcon,
                                  "text-sm text-white"
                         )}></i>
                       </div>
                              <div className="flex-1 min-w-0">
                                <div className="flex items-center space-x-2">
                                  <h4 className="font-mono font-semibold text-sm truncate">{project.projectName}</h4>
                                  {/* 项目类型标识 */}
                                  {(project as any).type === 'OWNER' && (
                                    <span className={cn(
                                      "px-1.5 py-0.5 rounded-full text-xs font-medium flex-shrink-0",
                                      "bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300"
                                    )}>
                                      <i className="fa-solid fa-crown mr-0.5"></i>
                                      拥有者
                                    </span>
                                  )}
                                  {(project as any).type === 'PARTICIPANT' && (
                                    <span className={cn(
                                      "px-1.5 py-0.5 rounded-full text-xs font-medium flex-shrink-0",
                                      "bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300"
                                    )}>
                                      <i className="fa-solid fa-user mr-0.5"></i>
                                      参与者
                                    </span>
                                  )}
                                </div>
                                <p className="text-xs text-gray-500 truncate">{project.projectDesc || '暂无描述'}</p>
                     </div>
                            </div>
                            
                            <div className="pt-1 border-t border-gray-200 dark:border-gray-700">
                              <div className="flex items-center justify-between text-xs text-gray-500">
                                <span>创建者: {project.createUser?.userName || '未知'}</span>
                                <span>{new Date(project.createTime).toLocaleDateString()}</span>
                              </div>
                            </div>
                          </div>

                          {/* 悬停效果 */}
                          <div className="absolute inset-0 rounded-xl bg-gradient-to-r from-blue-500/5 to-purple-500/5 opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
                   </motion.div>
                ))}
               </div>
                  ) : (
                    <motion.div
                      initial={{ opacity: 0, y: 20 }}
                      animate={{ opacity: 1, y: 0 }}
                      className={cn(
                        "p-8 rounded-xl border-2 border-dashed text-center",
                        isDark ? "border-gray-700 bg-gray-800/50" : "border-gray-300 bg-gray-50"
                      )}
                    >
                      <div className="mb-3">
                        <i className="fa-solid fa-folder-open text-3xl text-gray-400"></i>
            </div>
                      <h4 className="text-base font-mono mb-1">还没有项目</h4>
                      <p className="text-gray-500 mb-4">创建第一个项目开始协作</p>
                      <button
                        onClick={() => setShowCreateProjectModal(true)}
                        className={cn(
                          "px-4 py-2 rounded-lg font-medium transition-all duration-200",
                          isDark 
                            ? "bg-gradient-to-r from-orange-600 to-red-600 hover:from-orange-700 hover:to-red-700" 
                            : "bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600",
                          "text-white shadow-lg hover:shadow-xl"
                        )}
                      >
                        <i className="fa-solid fa-plus mr-2"></i>
                        创建项目
                      </button>
                    </motion.div>
                  )}
                </div>
              </motion.div>
          </div>
        )}
      </main>

      {/* 新建团队模态框 */}
      {showCreateModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <motion.div
            initial={{ opacity: 0, y: 20, scale: 0.95 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: 20, scale: 0.95 }}
            className={cn(
              "w-full max-w-md max-h-[90vh] rounded-2xl shadow-2xl border flex flex-col",
              isDark ? "bg-gray-800 border-gray-700" : "bg-white border-gray-200"
            )}
          >
            <div className="flex justify-between items-center p-6 border-b border-gray-200 dark:border-gray-700 flex-shrink-0">
              <div>
                <h2 className="font-mono font-bold text-2xl">新建团队</h2>
                <p className="text-gray-500 text-sm mt-1">创建一个新的团队开始协作</p>
              </div>
              <button
                onClick={() => setShowCreateModal(false)}
                className={cn(
                  "w-8 h-8 rounded-lg flex items-center justify-center transition-all duration-200",
                  isDark ? "hover:bg-gray-700" : "hover:bg-gray-100"
                )}
              >
                <i className="fa-solid fa-times"></i>
              </button>
            </div>
            <div className="flex-1 overflow-y-auto p-6 space-y-6">
              <div>
                <label className="block font-mono text-sm font-medium mb-2">团队名称</label>
                <input
                  type="text"
                  value={newTeam.teamName}
                  onChange={(e) => setNewTeam({...newTeam, teamName: e.target.value})}
                  className={cn(
                    "w-full px-4 py-3 rounded-xl border font-mono transition-all duration-200",
                    "focus:outline-none focus:ring-2 focus:ring-offset-2",
                    isDark 
                      ? "border-gray-700 focus:ring-blue-500 bg-gray-700 focus:border-blue-500" 
                      : "border-gray-300 focus:ring-orange-500 bg-white focus:border-orange-500"
                  )}
                  placeholder="输入团队名称"
                />
              </div>
              <div>
                <label className="block font-mono text-sm font-medium mb-3">团队图标</label>
                <div className="grid grid-cols-6 gap-3">
                  {iconOptions.map(icon => (
                    <button
                      key={icon}
                      onClick={() => setNewTeam({...newTeam, teamIcon: icon})}
                      className={cn(
                        "p-3 rounded-xl flex items-center justify-center transition-all duration-200",
                        "hover:scale-105",
                        newTeam.teamIcon === icon 
                          ? (isDark ? "bg-gradient-to-br from-blue-600 to-purple-600 shadow-lg" : "bg-gradient-to-br from-orange-500 to-red-500 shadow-lg") 
                          : (isDark ? "hover:bg-gray-700" : "hover:bg-gray-100")
                      )}
                    >
                      <i className={cn(
                        icon,
                        "text-xl",
                        newTeam.teamIcon === icon ? "text-white" : 
                          (isDark ? "text-blue-400" : "text-orange-500")
                      )}></i>
                    </button>
                  ))}
                </div>
              </div>
              <div>
                <label className="block font-mono text-sm font-medium mb-2">团队描述</label>
                <textarea
                  value={newTeam.desc}
                  onChange={(e) => setNewTeam({...newTeam, desc: e.target.value})}
                  className={cn(
                    "w-full px-4 py-3 rounded-xl border font-mono transition-all duration-200",
                    "focus:outline-none focus:ring-2 focus:ring-offset-2",
                    isDark 
                      ? "border-gray-700 focus:ring-blue-500 bg-gray-700 focus:border-blue-500" 
                      : "border-gray-300 focus:ring-orange-500 bg-white focus:border-orange-500"
                  )}
                  placeholder="输入团队描述（可选）"
                  rows={3}
                />
              </div>
            </div>
            <div className="flex justify-end space-x-3 p-6 border-t border-gray-200 dark:border-gray-700 flex-shrink-0">
                <button
                  onClick={() => setShowCreateModal(false)}
                  className={cn(
                  "px-6 py-2 rounded-lg font-medium transition-all duration-200",
                    isDark 
                      ? "bg-gray-700 hover:bg-gray-600" 
                      : "bg-gray-200 hover:bg-gray-300"
                  )}
                >
                  取消
                </button>
                <button
                  onClick={handleCreateTeam}
                  className={cn(
                  "px-6 py-2 rounded-lg font-medium transition-all duration-200 transform hover:scale-105",
                    isDark 
                    ? "bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700" 
                    : "bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600",
                  "text-white shadow-lg hover:shadow-xl"
                )}
              >
                创建团队
                </button>
            </div>
          </motion.div>
        </div>
      )}
       {/* 添加成员模态框 */}
       {showAddMemberModal && selectedTeam && (
         <AddUserModal
           isOpen={showAddMemberModal}
           onClose={() => setShowAddMemberModal(false)}
           onAddUsers={async (users) => {
             if (users.length === 0) {
               // 移除成员操作或刷新请求
               console.log('Removing members from team or refresh request');
               // 刷新团队成员数据
               try {
                 const members = await UserService.getTeamMembers(selectedTeam);
                 setMembers(members);
               } catch (error) {
                 console.error('刷新团队成员失败:', error);
               }
             } else {
               // 添加成员操作
               console.log('Adding users to team');
             
             // 更新本地团队成员列表
             const updatedTeams = teams.map(team => {
               if (team.teamId === selectedTeam) {
                 return {
                  ...team,
                  members: [
                    ...team.members,
                    ...users.map(user => ({
                      userId: user.userId,
                      userName: user.userName,
                      userIcon: user.userIcon,
                      account: user.account
                    }))
                  ]
                };
              }
              return team;
            });

            setTeams(updatedTeams);
            
            // 刷新团队成员数据
            try {
              const members = await UserService.getTeamMembers(selectedTeam);
              setMembers(members);
            } catch (error) {
              console.error('刷新团队成员失败:', error);
              }
            }
            
             // 不关闭弹框，让用户可以继续操作
             // setShowAddMemberModal(false);
          }}
          isDark={isDark}
          existingUsers={members.map(member => ({
            userId: member.userId,
            userName: member.userName,
            userIcon: member.userIcon,
            account: member.account,
            type: member.type // 确保传递成员类型信息
          }))}
          teamId={selectedTeam}
        />
      )}

      {/* 编辑团队模态框 */}
      {editingTeam && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <motion.div
            initial={{ opacity: 0, y: 20, scale: 0.95 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: 20, scale: 0.95 }}
            className={cn(
              "w-full max-w-md max-h-[90vh] rounded-2xl shadow-2xl border flex flex-col",
              isDark ? "bg-gray-800 border-gray-700" : "bg-white border-gray-200"
            )}
          >
            <div className="flex justify-between items-center p-6 border-b border-gray-200 dark:border-gray-700 flex-shrink-0">
              <div>
                <h2 className="font-mono font-bold text-2xl">编辑团队</h2>
                <p className="text-gray-500 text-sm mt-1">修改团队信息和设置</p>
              </div>
              <button
                onClick={() => setEditingTeam(null)}
                className={cn(
                  "w-8 h-8 rounded-lg flex items-center justify-center transition-all duration-200",
                  isDark ? "hover:bg-gray-700" : "hover:bg-gray-100"
                )}
              >
                <i className="fa-solid fa-times"></i>
              </button>
            </div>
            <div className="flex-1 overflow-y-auto p-6 space-y-6">
              <div>
                <label className="block font-mono text-sm font-medium mb-2">创建者</label>
                <div className={cn(
                  "p-4 rounded-xl flex items-center space-x-3",
                  isDark ? "bg-gray-700/50 border border-gray-600" : "bg-gray-50 border border-gray-200"
                )}>
                  <div className={cn(
                    "w-10 h-10 rounded-xl flex items-center justify-center",
                    isDark ? "bg-gradient-to-br from-blue-600 to-purple-600" : "bg-gradient-to-br from-orange-500 to-red-500"
                )}>
                  <i className={cn(
                    editingTeam.createUser.userIcon,
                      "text-lg text-white"
                    )}></i>
                  </div>
                  <div>
                    <p className="font-mono font-medium">{editingTeam.createUser.userName}</p>
                    <p className="text-sm text-gray-500">{editingTeam.createUser.account}</p>
                  </div>
                </div>
              </div>
              <div>
                <label className="block font-mono text-sm font-medium mb-2">团队名称</label>
                <input
                  type="text"
                  value={editingTeam.teamName}
                  onChange={(e) => setEditingTeam({...editingTeam, teamName: e.target.value})}
                  className={cn(
                    "w-full px-4 py-3 rounded-xl border font-mono transition-all duration-200",
                    "focus:outline-none focus:ring-2 focus:ring-offset-2",
                    isDark 
                      ? "border-gray-700 focus:ring-blue-500 bg-gray-700 focus:border-blue-500" 
                      : "border-gray-300 focus:ring-orange-500 bg-white focus:border-orange-500"
                  )}
                  placeholder="输入团队名称"
                />
              </div>
              <div>
                <label className="block font-mono text-sm font-medium mb-3">团队图标</label>
                <div className="grid grid-cols-6 gap-3">
                  {iconOptions.map(icon => (
                    <button
                      key={icon}
                      onClick={() => setEditingTeam({...editingTeam, teamIcon: icon})}
                      className={cn(
                        "p-3 rounded-xl flex items-center justify-center transition-all duration-200",
                        "hover:scale-105",
                        editingTeam.teamIcon === icon 
                          ? (isDark ? "bg-gradient-to-br from-blue-600 to-purple-600 shadow-lg" : "bg-gradient-to-br from-orange-500 to-red-500 shadow-lg") 
                          : (isDark ? "hover:bg-gray-700" : "hover:bg-gray-100")
                      )}
                    >
                      <i className={cn(
                        icon,
                        "text-xl",
                        editingTeam.teamIcon === icon ? "text-white" : 
                          (isDark ? "text-blue-400" : "text-orange-500")
                      )}></i>
                    </button>
                  ))}
                </div>
              </div>
              <div>
                <label className="block font-mono text-sm font-medium mb-2">团队描述</label>
                <textarea
                  value={editingTeam.desc}
                  onChange={(e) => setEditingTeam({...editingTeam, desc: e.target.value})}
                  className={cn(
                    "w-full px-4 py-3 rounded-xl border font-mono transition-all duration-200",
                    "focus:outline-none focus:ring-2 focus:ring-offset-2",
                    isDark 
                      ? "border-gray-700 focus:ring-blue-500 bg-gray-700 focus:border-blue-500" 
                      : "border-gray-300 focus:ring-orange-500 bg-white focus:border-orange-500"
                  )}
                  placeholder="输入团队描述（可选）"
                  rows={3}
                />
              </div>
            </div>
            <div className="flex justify-end space-x-3 p-6 border-t border-gray-200 dark:border-gray-700 flex-shrink-0">
                <button
                  onClick={() => setEditingTeam(null)}
                  className={cn(
                  "px-6 py-2 rounded-lg font-medium transition-all duration-200",
                    isDark 
                      ? "bg-gray-700 hover:bg-gray-600" 
                      : "bg-gray-200 hover:bg-gray-300"
                  )}
                >
                  取消
                </button>
                 <button
                   onClick={handleUpdateTeam}
                   disabled={isUpdatingTeam}
                   className={cn(
                  "px-6 py-2 rounded-lg font-medium transition-all duration-200 transform hover:scale-105",
                     isDark 
                    ? "bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700" 
                    : "bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600",
                  "text-white shadow-lg hover:shadow-xl",
                  isUpdatingTeam ? "opacity-75 cursor-not-allowed" : ""
                   )}
                 >
                   {isUpdatingTeam ? (
                     <>
                       <i className="fa-solid fa-spinner fa-spin mr-2"></i>
                       保存中...
                     </>
                ) : (
                  "保存更改"
                )}
                 </button>
            </div>
          </motion.div>
        </div>
       )}

      {/* 新建项目模态框 */}
      {showCreateProjectModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <motion.div
            initial={{ opacity: 0, y: 20, scale: 0.95 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: 20, scale: 0.95 }}
            className={cn(
              "w-full max-w-md max-h-[90vh] rounded-2xl shadow-2xl border flex flex-col",
              isDark ? "bg-gray-800 border-gray-700" : "bg-white border-gray-200"
            )}
          >
            <div className="flex justify-between items-center p-6 border-b border-gray-200 dark:border-gray-700 flex-shrink-0">
              <h2 className="font-mono font-bold text-2xl">新建项目</h2>
              <button
                onClick={() => setShowCreateProjectModal(false)}
                className={cn(
                  "w-8 h-8 rounded-lg flex items-center justify-center transition-all duration-200",
                  isDark ? "hover:bg-gray-700" : "hover:bg-gray-100"
                )}
              >
                <i className="fa-solid fa-times"></i>
              </button>
            </div>
            <div className="flex-1 overflow-y-auto p-6 space-y-6">
              <div>
                <label className="block font-mono text-sm font-medium mb-2">项目名称</label>
                <input
                  type="text"
                  value={newProject.projectName}
                  onChange={(e) => setNewProject({...newProject, projectName: e.target.value})}
                  className={cn(
                    "w-full px-4 py-3 rounded-xl border font-mono transition-all duration-200",
                    "focus:outline-none focus:ring-2 focus:ring-offset-2",
                    isDark 
                      ? "border-gray-700 focus:ring-blue-500 bg-gray-700 focus:border-blue-500" 
                      : "border-gray-300 focus:ring-orange-500 bg-white focus:border-orange-500"
                  )}
                  placeholder="输入项目名称"
                />
              </div>
              <div>
                <label className="block font-mono text-sm font-medium mb-3">项目图标</label>
                <div className="grid grid-cols-6 gap-3">
                  {iconOptions.map(icon => (
                    <button
                      key={icon}
                      onClick={() => setNewProject({...newProject, projectIcon: icon})}
                      className={cn(
                        "p-3 rounded-xl flex items-center justify-center transition-all duration-200",
                        "hover:scale-105",
                        newProject.projectIcon === icon 
                          ? (isDark ? "bg-gradient-to-br from-blue-600 to-purple-600 shadow-lg" : "bg-gradient-to-br from-orange-500 to-red-500 shadow-lg") 
                          : (isDark ? "hover:bg-gray-700" : "hover:bg-gray-100")
                      )}
                    >
                      <i className={cn(
                        icon,
                        "text-xl",
                        newProject.projectIcon === icon ? "text-white" : 
                          (isDark ? "text-blue-400" : "text-orange-500")
                      )}></i>
                    </button>
                  ))}
                </div>
              </div>
              <div>
                <label className="block font-mono text-sm font-medium mb-2">项目描述</label>
                <textarea
                  value={newProject.projectDesc}
                  onChange={(e) => setNewProject({...newProject, projectDesc: e.target.value})}
                  className={cn(
                    "w-full px-4 py-3 rounded-xl border font-mono transition-all duration-200",
                    "focus:outline-none focus:ring-2 focus:ring-offset-2",
                    isDark 
                      ? "border-gray-700 focus:ring-blue-500 bg-gray-700 focus:border-blue-500" 
                      : "border-gray-300 focus:ring-orange-500 bg-white focus:border-orange-500"
                  )}
                  placeholder="输入项目描述（可选）"
                  rows={3}
                />
              </div>
            </div>
            <div className="flex justify-end space-x-3 p-6 border-t border-gray-200 dark:border-gray-700 flex-shrink-0">
                <button
                  onClick={() => setShowCreateProjectModal(false)}
                  className={cn(
                  "px-6 py-2 rounded-lg font-medium transition-all duration-200",
                    isDark 
                      ? "bg-gray-700 hover:bg-gray-600" 
                      : "bg-gray-200 hover:bg-gray-300"
                  )}
                >
                  取消
                </button>
                <button
                   onClick={async () => {
                    if (!newProject.projectName.trim()) {
                      toast.error("项目名称不能为空");
                      return;
                    }

                    try {
                      const res = await UserService.addProject({
                        teamId: selectedTeam || "",
                        projectName: newProject.projectName,
                        projectIcon: newProject.projectIcon,
                      projectDesc: newProject.projectDesc
                      });

                      if (res.success) {
                        // 新建项目后刷新该团队的项目列表
                        try {
                          const projects = await UserService.getProjectListByTeamId(selectedTeam || "");
                          const updatedTeams = teams.map(team => {
                            if (team.teamId === selectedTeam) {
                              return {
                                ...team,
                                projects: projects.map((project: any) => ({
                                  ...project,
                                  type: project.type || 'PARTICIPANT'
                                }))
                              };
                            }
                            return team;
                          });
                          setTeams(updatedTeams);
                        } catch (e) {}
                        setShowCreateProjectModal(false);
                        setNewProject({
                          projectName: "",
                          projectIcon: "fa-solid fa-folder",
                          projectDesc: ""
                        });
                        toast.success(`项目 ${newProject.projectName} 创建成功`);
                        // 新建项目成功后，也调用 fetchCurrentTeamProjects(selectedTeam)
                        fetchCurrentTeamProjects(selectedTeam);
                      }
                    } catch (error: any) {
                      console.error('创建项目错误:', error);
                      toast.error(error.message || '创建项目失败');
                    }
                  }}
                  className={cn(
                  "px-6 py-2 rounded-lg font-medium transition-all duration-200 transform hover:scale-105",
                    isDark 
                    ? "bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700" 
                    : "bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600",
                  "text-white shadow-lg hover:shadow-xl"
                )}
              >
                创建项目
                </button>
            </div>
          </motion.div>
        </div>
      )}

      {/* 编辑项目模态框 */}
      {editingProject && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <motion.div
            initial={{ opacity: 0, y: 20, scale: 0.95 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: 20, scale: 0.95 }}
            className={cn(
              "w-full max-w-md max-h-[90vh] rounded-2xl shadow-2xl border flex flex-col",
              isDark ? "bg-gray-800 border-gray-700" : "bg-white border-gray-200"
            )}
          >
            <div className="flex justify-between items-center p-6 border-b border-gray-200 dark:border-gray-700 flex-shrink-0">
              <div>
                <h2 className="font-mono font-bold text-2xl">编辑项目</h2>
                <p className="text-gray-500 text-sm mt-1">修改项目信息和设置</p>
              </div>
              <button
                onClick={() => setEditingProject(null)}
                className={cn(
                  "w-8 h-8 rounded-lg flex items-center justify-center transition-all duration-200",
                  isDark ? "hover:bg-gray-700" : "hover:bg-gray-100"
                )}
              >
                <i className="fa-solid fa-times"></i>
              </button>
            </div>
            <div className="flex-1 overflow-y-auto p-6 space-y-6">
              <div>
                <label className="block font-mono text-sm font-medium mb-2">项目名称</label>
                <input
                  type="text"
                  value={editingProject.projectName}
                  onChange={(e) => setEditingProject({...editingProject, projectName: e.target.value})}
                  className={cn(
                    "w-full px-4 py-3 rounded-xl border font-mono transition-all duration-200",
                    "focus:outline-none focus:ring-2 focus:ring-offset-2",
                    isDark 
                      ? "border-gray-700 focus:ring-blue-500 bg-gray-700 focus:border-blue-500" 
                      : "border-gray-300 focus:ring-orange-500 bg-white focus:border-orange-500"
                  )}
                  placeholder="输入项目名称"
                />
              </div>
              <div>
                <label className="block font-mono text-sm font-medium mb-3">项目图标</label>
                <div className="grid grid-cols-6 gap-3">
                  {iconOptions.map(icon => (
                    <button
                      key={icon}
                      onClick={() => setEditingProject({...editingProject, projectIcon: icon})}
                      className={cn(
                        "p-3 rounded-xl flex items-center justify-center transition-all duration-200",
                        "hover:scale-105",
                        editingProject.projectIcon === icon 
                          ? (isDark ? "bg-gradient-to-br from-blue-600 to-purple-600 shadow-lg" : "bg-gradient-to-br from-orange-500 to-red-500 shadow-lg") 
                          : (isDark ? "hover:bg-gray-700" : "hover:bg-gray-100")
                      )}
                    >
                      <i className={cn(
                        icon,
                        "text-xl",
                        editingProject.projectIcon === icon ? "text-white" : 
                          (isDark ? "text-blue-400" : "text-orange-500")
                      )}></i>
                    </button>
                  ))}
                </div>
              </div>
              <div>
                <label className="block font-mono text-sm font-medium mb-2">项目描述</label>
                <textarea
                  value={editingProject.projectDesc}
                  onChange={(e) => setEditingProject({...editingProject, projectDesc: e.target.value})}
                  className={cn(
                    "w-full px-4 py-3 rounded-xl border font-mono transition-all duration-200",
                    "focus:outline-none focus:ring-2 focus:ring-offset-2",
                    isDark 
                      ? "border-gray-700 focus:ring-blue-500 bg-gray-700 focus:border-blue-500" 
                      : "border-gray-300 focus:ring-orange-500 bg-white focus:border-orange-500"
                  )}
                  placeholder="输入项目描述（可选）"
                  rows={3}
                />
              </div>
            </div>
            <div className="flex justify-end space-x-3 p-6 border-t border-gray-200 dark:border-gray-700 flex-shrink-0">
                <button
                  onClick={() => setEditingProject(null)}
                  className={cn(
                  "px-6 py-2 rounded-lg font-medium transition-all duration-200",
                    isDark 
                      ? "bg-gray-700 hover:bg-gray-600" 
                      : "bg-gray-200 hover:bg-gray-300"
                  )}
                >
                  取消
                </button>
                <button
                  onClick={async () => {
                    if (!editingProject.projectName.trim()) {
                      toast.error("项目名称不能为空");
                      return;
                    }

                    try {
                      const res = await UserService.editProject({
                        projectId: editingProject.projectId,
                        projectName: editingProject.projectName,
                        projectIcon: editingProject.projectIcon,
                      projectDesc: editingProject.projectDesc
                      });

                      if (res.success) {
                        const updatedTeams = teams.map(team => {
                          if (team.teamId === selectedTeam) {
                            return {
                              ...team,
                              projects: team.projects?.map(p => 
                                p.projectId === editingProject.projectId ? editingProject : p
                              ) || []
                            };
                          }
                          return team;
                        });

                        setTeams(updatedTeams);
                        setEditingProject(null);
                        toast.success("项目信息已更新");
                        if (selectedTeam) fetchCurrentTeamProjects(selectedTeam); // 新增：刷新项目列表
                      }
                    } catch (error: any) {
                      console.error('更新项目失败:', error);
                      toast.error(
                        <div className="space-y-1">
                          <div className="font-medium">更新项目失败</div>
                          <div className="text-sm">{error.message}</div>
                        </div>
                      );
                    }
                  }}
                  className={cn(
                  "px-6 py-2 rounded-lg font-medium transition-all duration-200 transform hover:scale-105",
                    isDark 
                    ? "bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700" 
                    : "bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600",
                  "text-white shadow-lg hover:shadow-xl"
                )}
              >
                保存更改
                </button>
            </div>
          </motion.div>
        </div>
       )}

      {/* 移除成员确认弹框 */}
      {showRemoveConfirm.show && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <motion.div
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            exit={{ opacity: 0, scale: 0.9 }}
            className={cn(
              "w-full max-w-md p-8 rounded-2xl shadow-2xl border",
              isDark ? "bg-gray-800 border-gray-700" : "bg-white border-gray-200"
            )}
          >
            <div className="flex items-start space-x-4">
              <div className={cn(
                "flex-shrink-0 w-12 h-12 rounded-xl flex items-center justify-center",
                isDark ? "bg-red-900/30" : "bg-red-100"
              )}>
                <i className="fa-solid fa-user-slash text-xl text-red-500"></i>
              </div>
              <div className="flex-1">
                <h3 className="font-mono text-xl font-semibold mb-2">确认移除成员</h3>
                <p className="text-gray-500 mb-6">
                  确定要将 <span className="font-medium text-gray-700 dark:text-gray-300">{showRemoveConfirm.memberName}</span> 移出团队吗？
                </p>
                <p className="text-sm text-gray-400 mb-6">
                  此操作不可撤销，移除后该成员将无法访问团队内的项目和文档。
                </p>
                <div className="flex justify-end space-x-3">
                  <button
                    onClick={() => setShowRemoveConfirm({ show: false, memberId: "", memberName: "" })}
                    className={cn(
                      "px-6 py-2 rounded-lg font-medium transition-all duration-200",
                      isDark ? "bg-gray-700 hover:bg-gray-600" : "bg-gray-200 hover:bg-gray-300"
                    )}
                  >
                    取消
                  </button>
                  <button
                    onClick={async () => {
                      await handleRemoveMember(showRemoveConfirm.memberId);
                        setShowRemoveConfirm({ show: false, memberId: "", memberName: "" });
                    }}
                    className={cn(
                      "px-6 py-2 rounded-lg font-medium transition-all duration-200 transform hover:scale-105",
                      "bg-gradient-to-r from-red-500 to-pink-500 hover:from-red-600 hover:to-pink-600",
                      "text-white shadow-lg hover:shadow-xl"
                    )}
                  >
                    确认移除
                  </button>
                </div>
              </div>
            </div>
          </motion.div>
        </div>
      )}

      {/* 团队设置弹框 */}
      {showTeamSettingsModal && selectedTeam && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <motion.div
            initial={{ opacity: 0, y: 20, scale: 0.95 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: 20, scale: 0.95 }}
            className={cn(
              "w-full max-w-md max-h-[90vh] rounded-2xl shadow-2xl border flex flex-col",
              isDark ? "bg-gray-800 border-gray-700" : "bg-white border-gray-200"
            )}
          >
            <div className="flex justify-between items-center p-6 border-b border-gray-200 dark:border-gray-700 flex-shrink-0">
              <div>
                <h2 className="font-mono font-bold text-2xl">团队设置</h2>
                <p className="text-gray-500 text-sm mt-1">管理团队信息和成员</p>
    </div>
              <button
                onClick={() => setShowTeamSettingsModal(false)}
                className={cn(
                  "w-8 h-8 rounded-lg flex items-center justify-center transition-all duration-200",
                  isDark ? "hover:bg-gray-700" : "hover:bg-gray-100"
                )}
              >
                <i className="fa-solid fa-times"></i>
              </button>
            </div>
            
            <div className="flex-1 overflow-y-auto p-6 space-y-4">
              {/* 团队信息 */}
              <div className={cn(
                "p-4 rounded-xl border",
                isDark ? "bg-gray-700/50 border-gray-600" : "bg-gray-50 border-gray-200"
              )}>
                <div className="flex items-center space-x-3 mb-3">
                  <div className={cn(
                    "w-10 h-10 rounded-lg flex items-center justify-center",
                    isDark ? "bg-gradient-to-br from-blue-600 to-purple-600" : "bg-gradient-to-br from-orange-500 to-red-500"
                  )}>
                    <i className={cn(
                      currentTeam?.teamIcon,
                      "text-lg text-white"
                    )}></i>
                  </div>
                  <div>
                    <h3 className="font-mono font-semibold">{currentTeam?.teamName}</h3>
                    <p className="text-sm text-gray-500">{currentTeam?.desc || '暂无描述'}</p>
                  </div>
                </div>
                <div className="text-xs text-gray-500">
                  {members.length}位成员 · {currentTeam?.projects?.length || 0}个项目
                </div>
              </div>

              {/* 操作按钮 */}
              <div className="space-y-3">
                {(() => {
                  const userTeam = userInfo?.teamList.find(t => t.teamId === selectedTeam);
                  const isOwner = userTeam?.type === 'OWNER';
                  
                  return (
                    <>
                      {/* 拥有者功能 */}
                      {isOwner && (
                        <>
                          {/* 编辑团队 */}
                          <button
                            onClick={() => {
                              const team = teams.find(t => t.teamId === selectedTeam);
                              if (team) {
                                setEditingTeam(team);
                                setShowTeamSettingsModal(false);
                              }
                            }}
                            className={cn(
                              "w-full p-4 rounded-xl border transition-all duration-200 flex items-center space-x-3",
                              "hover:scale-105",
                              isDark 
                                ? "bg-gray-700 border-gray-600 hover:bg-gray-600" 
                                : "bg-gray-50 border-gray-200 hover:bg-gray-50"
                            )}
                          >
                            <div className={cn(
                              "w-10 h-10 rounded-lg flex items-center justify-center",
                              isDark ? "bg-blue-600" : "bg-blue-500"
                            )}>
                              <i className="fa-solid fa-pen text-white"></i>
                            </div>
                            <div className="text-left">
                              <div className="font-medium">编辑团队</div>
                              <div className="text-sm text-gray-500">修改团队名称和描述</div>
                            </div>
                          </button>

                          {/* 添加成员 */}
                          <button
                            onClick={() => {
                              setShowAddMemberModal(true);
                              setShowTeamSettingsModal(false);
                            }}
                            className={cn(
                              "w-full p-4 rounded-xl border transition-all duration-200 flex items-center space-x-3",
                              "hover:scale-105",
                              isDark 
                                ? "bg-gray-700 border-gray-600 hover:bg-gray-600" 
                                : "bg-gray-50 border-gray-200 hover:bg-gray-50"
                            )}
                          >
                            <div className={cn(
                              "w-10 h-10 rounded-lg flex items-center justify-center",
                              isDark ? "bg-green-600" : "bg-green-500"
                            )}>
                              <i className="fa-solid fa-user-plus text-white"></i>
                            </div>
                            <div className="text-left">
                              <div className="font-medium">添加成员</div>
                              <div className="text-sm text-gray-500">邀请新成员加入团队</div>
                            </div>
                          </button>

                          {/* 删除团队 */}
                          <button
                            onClick={async () => {
                              setShowTeamSettingsModal(false);
                              
                              const confirmed = await confirm.danger(
                                '删除团队',
                                `确定要删除团队 "${currentTeam?.teamName}" 吗？\n\n⚠️ 警告：此操作将删除该团队下的所有项目和文档，且无法恢复！`,
                                '删除',
                                '取消'
                              );
                              
                              if (confirmed) {
                                await handleDeleteTeam(selectedTeam);
                              }
                            }}
                            className={cn(
                              "w-full p-4 rounded-xl border transition-all duration-200 flex items-center space-x-3",
                              "hover:scale-105",
                              isDark 
                                ? "bg-red-900/20 border-red-600 hover:bg-red-900/30" 
                                : "bg-red-50 border-red-200 hover:bg-red-100"
                            )}
                          >
                            <div className={cn(
                              "w-10 h-10 rounded-lg flex items-center justify-center",
                              "bg-red-500"
                            )}>
                              <i className="fa-solid fa-trash text-white"></i>
                            </div>
                            <div className="text-left">
                              <div className="font-medium">删除团队</div>
                              <div className="text-sm text-gray-500">永久删除团队及其所有内容</div>
                            </div>
                          </button>
                        </>
                      )}

                      {/* 参与者功能 */}
                      {!isOwner && (
                        <>
                          {/* 退出团队 */}
                          <button
                            onClick={async () => {
                              setShowTeamSettingsModal(false);
                              
                              const confirmed = await confirm.warning(
                                '退出团队',
                                `确定要退出团队 "${currentTeam?.teamName}" 吗？\n\n退出后您将无法访问该团队的项目和文档。`,
                                '退出',
                                '取消'
                              );
                              
                              if (confirmed) {
                                await handleLeaveTeam(selectedTeam);
                              }
                            }}
                            className={cn(
                              "w-full p-4 rounded-xl border transition-all duration-200 flex items-center space-x-3",
                              "hover:scale-105",
                              isDark 
                                ? "bg-orange-900/20 border-orange-600 hover:bg-orange-900/30" 
                                : "bg-orange-50 border-orange-200 hover:bg-orange-100"
                            )}
                          >
                            <div className={cn(
                              "w-10 h-10 rounded-lg flex items-center justify-center",
                              "bg-orange-500"
                            )}>
                              <i className="fa-solid fa-sign-out-alt text-white"></i>
                            </div>
                            <div className="text-left">
                              <div className="font-medium">退出团队</div>
                              <div className="text-sm text-gray-500">退出当前团队</div>
                            </div>
                          </button>
                        </>
                      )}
                    </>
                  );
                })()}
              </div>
            </div>
          </motion.div>
        </div>
      )}

      {/* 项目成员管理模态框 */}
      {showProjectMembersModal && selectedProjectForMembers && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <motion.div
            initial={{ opacity: 0, y: 20, scale: 0.95 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: 20, scale: 0.95 }}
            className={cn(
              "w-full max-w-2xl max-h-[90vh] rounded-2xl shadow-2xl border flex flex-col",
              isDark ? "bg-gray-800 border-gray-700" : "bg-white border-gray-200"
            )}
          >
            <div className="flex justify-between items-center p-6 border-b border-gray-200 dark:border-gray-700 flex-shrink-0">
              <div>
                <h2 className="font-mono font-bold text-2xl">项目成员</h2>
                <p className="text-gray-500 text-sm mt-1">{selectedProjectForMembers.projectName}</p>
              </div>
              <button
                onClick={() => setShowProjectMembersModal(false)}
                className={cn(
                  "w-8 h-8 rounded-lg flex items-center justify-center transition-all duration-200",
                  isDark ? "hover:bg-gray-700" : "hover:bg-gray-100"
                )}
              >
                <i className="fa-solid fa-times"></i>
              </button>
            </div>
            
            <div className="flex-1 overflow-y-auto p-6">
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {/* 左侧：添加团队成员到项目 */}
                <div>
                  <h3 className="font-mono font-semibold text-lg mb-4">添加团队成员</h3>
                  <div className="space-y-3">
                    {members
                      .filter(member => !currentProjectMembers.some(pm => pm.userId === member.userId))
                      .map((member) => (
                        <div
                          key={member.userId}
                          className={cn(
                            "p-3 rounded-lg border flex items-center justify-between",
                            isDark ? "bg-gray-700 border-gray-600" : "bg-gray-50 border-gray-200"
                          )}
                        >
                          <div className="flex items-center space-x-3">
                            <div className={cn(
                              "w-8 h-8 rounded-lg flex items-center justify-center",
                              isDark ? "bg-gradient-to-br from-green-600 to-blue-600" : "bg-gradient-to-br from-green-500 to-blue-500"
                            )}>
                              <i className={cn(
                                member.userIcon || "fa-solid fa-user",
                                "text-sm text-white"
                              )}></i>
                            </div>
                            <div>
                              <p className="font-medium text-sm">{member.userName}</p>
                              <p className="text-xs text-gray-500">{member.account}</p>
                            </div>
                          </div>
                          <div className="flex items-center space-x-2">
                            {/* 权限选择器 */}
                            <select
                              id={`permission-${member.userId}`}
                              className={cn(
                                "px-2 py-1 rounded text-xs border",
                                isDark ? "bg-gray-600 border-gray-500" : "bg-white border-gray-300"
                              )}
                            >
                              <option value="r">只读</option>
                              <option value="rw">读写</option>
                            </select>
                            
                            {/* 添加按钮 */}
                            <button
                              onClick={() => {
                                const permission = (document.getElementById(`permission-${member.userId}`) as HTMLSelectElement)?.value as 'r' | 'rw';
                                handleAddProjectMember(member.userId, permission);
                              }}
                              className={cn(
                                "px-3 py-1 rounded text-xs font-medium transition-colors duration-200",
                                isDark ? "bg-green-600 hover:bg-green-700" : "bg-green-500 hover:bg-green-600",
                                "text-white"
                              )}
                            >
                              添加
                            </button>
                          </div>
                        </div>
                      ))}
                    
                    {members.filter(member => !currentProjectMembers.some(pm => pm.userId === member.userId)).length === 0 && (
                      <div className={cn(
                        "p-4 rounded-lg border-2 border-dashed text-center",
                        isDark ? "border-gray-600 bg-gray-700/50" : "border-gray-300 bg-gray-50"
                      )}>
                        <i className="fa-solid fa-check-circle text-2xl text-green-400 mb-2"></i>
                        <p className="text-gray-500 text-sm">所有团队成员已加入项目</p>
                      </div>
                    )}
                  </div>
                </div>

                {/* 右侧：当前项目成员 */}
                <div>
                  <h3 className="font-mono font-semibold text-lg mb-4">当前项目成员</h3>
                  <div className="space-y-3">
                    {currentProjectMembers.map((member) => (
                      <div
                        key={member.userId}
                        className={cn(
                          "p-3 rounded-lg border flex items-center justify-between",
                          isDark ? "bg-gray-700 border-gray-600" : "bg-gray-50 border-gray-200"
                        )}
                      >
                        <div className="flex items-center space-x-3">
                          <div className={cn(
                            "w-8 h-8 rounded-lg flex items-center justify-center",
                            isDark ? "bg-gradient-to-br from-blue-600 to-purple-600" : "bg-gradient-to-br from-blue-500 to-purple-500"
                          )}>
                            <i className={cn(
                              member.userIcon || "fa-solid fa-user",
                              "text-sm text-white"
                            )}></i>
                          </div>
                          <div>
                            <p className="font-medium text-sm">{member.userName}</p>
                            <p className="text-xs text-gray-500">{member.account}</p>
                          </div>
                        </div>
                        <div className="flex items-center space-x-2">
                          {/* 权限选择器 */}
                          <select
                            value={member.permission || 'r'}
                            onChange={(e) => handleUpdateProjectPermission(member.userId, e.target.value as 'r' | 'rw')}
                            className={cn(
                              "px-2 py-1 rounded text-xs border",
                              isDark ? "bg-gray-600 border-gray-500" : "bg-white border-gray-300"
                            )}
                          >
                            <option value="r">只读</option>
                            <option value="rw">读写</option>
                          </select>
                          
                          {/* 移除按钮 */}
                          {member.userId !== (userInfo as any)?.userId && (
                            <button
                              onClick={() => handleRemoveProjectMember(member.userId)}
                              className={cn(
                                "w-6 h-6 rounded flex items-center justify-center transition-colors duration-200",
                                isDark ? "hover:bg-red-600 text-red-400" : "hover:bg-red-100 text-red-600"
                              )}
                              title="移除成员"
                            >
                              <i className="fa-solid fa-times text-xs"></i>
                            </button>
                          )}
                        </div>
                      </div>
                    ))}
                    
                    {currentProjectMembers.length === 0 && (
                      <div className={cn(
                        "p-4 rounded-lg border-2 border-dashed text-center",
                        isDark ? "border-gray-600 bg-gray-700/50" : "border-gray-300 bg-gray-50"
                      )}>
                        <i className="fa-solid fa-users text-2xl text-gray-400 mb-2"></i>
                        <p className="text-gray-500 text-sm">暂无项目成员</p>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </div>
          </motion.div>
        </div>
      )}
    </div>
  );
}